package com.ruoyi.wxapp;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.cms.domain.MemberOrder;
import com.ruoyi.cms.service.IMemberOrderService;
import com.ruoyi.wxapp.config.WeChatAppPayProperties;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * @author : Gentle
 * @date : 2019/5/17 12:38
 * @description:
 */
@RestController
@Slf4j
public class WeChatNoticeController {

    private static final String REFUND_SUCCESS = "SUCCESS";
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    WeChatAppPayProperties weChatPayProperties;

    private IMemberOrderService orderService;
      /**
    *
    * @param xmlData 微信返回的流
    * @return
    */
   @RequestMapping(value = "/app/public/wxapp/notify",method = {RequestMethod.GET,RequestMethod.POST})
   public String weChatNotify(@RequestBody String xmlData){

       try {

           System.out.println("我进入了支付以后消息通知的地方：===============================================");

           final WxPayOrderNotifyResult notifyResult = this.wxPayService.parseOrderNotifyResult(xmlData);
           //这里是存储我们发起支付时订单号的信息，所以取出来
           notifyResult.getOutTradeNo();
             /**
             * 系统内部业务，修改订单状态之类的
                                       支付成功后将信息放入订单表
                                       resultCode=FAIL, errCode=ORDERPAID
            */
          if(notifyResult.getReturnCode().equals("SUCCESS")) {
              if (notifyResult.getResultCode().equals("SUCCESS") || (
                      notifyResult.getResultCode().equals("FAIL") && notifyResult.getErrCode().equals("ORDERPAID"))) {
                  System.out.println("成功了：===============================================");

                  MemberOrder order = orderService.findByOrderCode(notifyResult.getOutTradeNo());
                  //钱直接进入代理商账户
                /*  if (order != null && order.getId() > 0) {
                      if (orderService.updatePayStatus(notifyResult.getOutTradeNo()) > 0) {
                          return WxPayNotifyResponse.success("回调成功！");
                      }
*/

                      //要发送小程序模板消息给客户
                      //1,配置小程序信息
                      //WxMaConfiguration wxConfig=WxMaConfiguration.getMaService(appid);
                      //WxMaConfig wxConfig=new WxMaDefaultConfigImpl();

                      /*WxMaService wxMaService = WxMaConfiguration.getMaService(ConstUtil.appid);
                      //2,设置模版信息（keyword1：类型，keyword2：内容）
                      List<WxMaTemplateData> templateDataList = new ArrayList<>(2);
                      WxMaTemplateData data1 = new WxMaTemplateData("keyword1", order.getOrderCode());
                      WxMaTemplateData data2 = new WxMaTemplateData("keyword2", "置顶服务费");
                      WxMaTemplateData data3 = new WxMaTemplateData("keyword3", order.getMoney()+"");
                      WxMaTemplateData data4 = new WxMaTemplateData("keyword4", order.getContent());
                      WxMaTemplateData data5 = new WxMaTemplateData("keyword5", DateUtils.formatDate(order.getCreateDate()));

                      templateDataList.add(data1);
                      templateDataList.add(data2);
                      templateDataList.add(data3);
                      templateDataList.add(data4);
                      templateDataList.add(data5);
                      System.out.println("order.getPrepay_id()======="+order.getPrepay_id());
        *//*
                      //3，设置推送消息
                      *//*WxMaTemplateMessage templateMessage = WxMaTemplateMessage.builder()
                              .toUser(order.getMember().getOpenid())//要推送的用户openid
                              .formId(order.getPrepay_id())//收集到的formid
                              //.templateId("eqc9VidnbKLhMcFPcE4SbaRkqlRQkOLYHUm73QOd0Uw")//推送的模版id（在小程序后台设置）
                              .templateId("4QIM0S1qHU05wksGez6WnEntHz-XBC0_3v7A81_xC94")//推送的模版id（在小程序后台设置）

                              .data(templateDataList)//模版信息
                              .page("pages/index/index")//要跳转到小程序那个页面
                              .build();*//*
                      //4，发起推送
                      *//*try {
                    	  wxMaService.getMsgService().sendTemplateMsg(templateMessage);
                      } catch (WxErrorException e) {
                          System.out.println("推送失败：" + e.getMessage());
                          //return e.getMessage();
                      }*//*
                     // return "推送成功";
                  }*/

                //  }
              }
              return WxPayNotifyResponse.success("回调成功！");

          }else{
              return WxPayNotifyResponse.fail("回调失败！");

          }
          //成功后回调微信信息
       } catch (WxPayException e) {
           e.printStackTrace();
           return WxPayNotifyResponse.fail("回调有误!");
       }
   }


    /**
     * 仅支持一次性退款，多次退款需要修改逻辑
     * @param xmlData 微信返回的流数据
     * @return
     */
    @RequestMapping(value = "/refundNotify",method = {RequestMethod.GET,RequestMethod.POST})
    public String refundNotify(@RequestBody String xmlData) {
        System.out.println("我进入了退款以后消息通知的地方：");
        WxPayRefundNotifyResult wxPayRefundNotifyResult;
        try {
            wxPayRefundNotifyResult = wxPayService.parseRefundNotifyResult(xmlData);
        } catch (WxPayException e) {
            log.error("退款失败，失败信息:{}", e);
            return WxPayNotifyResponse.fail("退款失败");
        }
        //判断你返回状态信息是否正确
        if (REFUND_SUCCESS.equals(wxPayRefundNotifyResult.getReturnCode())) {
            WxPayRefundNotifyResult.ReqInfo reqInfo = wxPayRefundNotifyResult.getReqInfo();
            //判断退款状态
            if (REFUND_SUCCESS.equals(reqInfo.getRefundStatus())) {
                //内部订单号
                String outTradeNo = reqInfo.getOutTradeNo();

                return WxPayNotifyResponse.success("退款成功！");
            }
        }

        return WxPayNotifyResponse.fail("回调有误!");
    }

    /**
     * 1 块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 时间
     *
     * @return 时间戳
     */
    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }




}